package com.joint.web.action.manage;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.*;
import com.joint.base.service.activiti.WorkflowService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.manage.*;
import com.joint.core.service.DispatchReviseService;
import com.joint.core.service.DispatchService;
import com.joint.core.service.TaskBackService;
import com.joint.core.service.TaskControlService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;


@ParentPackage("manage")
public class AjaxTaskbackAction extends BaseFlowAction {
    @Resource
    private WorkflowService workflowService;
    @Resource
    private TaskControlService taskControlService;
    @Resource
    private TaskBackService taskBackService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private PostService postService;
    @Resource
    private PowerService powerService;
    @Resource
    private DutyService dutyService;
    @Resource
    private UsersService usersService;
    @Resource
    private ReadersService readersService;
    @Resource
    private TaskRecordService taskRecordService;

    /**
     * 任务督办单(读)
     */
    private TaskControl taskControl;
    /**
     * 任务反馈单对象(读)
     */
    private TaskBack taskback;
    /**
     * 登录人(读)
     */
    private Users loginUser;

    /**
     * 附件上传Id(读)
     */
    private String fileId;

    /**
     * 完成程度
     */
    private String degree;

    /**
     * 实际完成时间
     */
    private String finishTime;
    /**
     * 任务反馈内容
     */
    private String content;

    /**
     * 附件上传Id
     */
    private String fileIds2;

    /**
     * 备注
     */
    private String remark;


    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "taskback";
    }



    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");

        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        //内嵌视图这里要加上
        if (StringUtils.isNotEmpty(parentId)){
            taskControl = taskControlService.get(parentId);
            params.put("taskControl",taskControl);
        }
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);

        //所有单子
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
        pager=taskBackService.findByPagerAndLimit(true, "taskback", pager, params);

        List<TaskBack>  taskBackList;
        if (pager.getTotalCount() > 0){
            taskBackList = (List<TaskBack>) pager.getList();
        }else{
            taskBackList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(TaskBack taskBack: taskBackList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",taskBack.getId());
            rMap.put("degree",taskBack.getDegree());
            rMap.put("creater", taskBack.getCreater() != null ? taskBack.getCreater().getName() : "");
            rMap.put("createDate", DataUtil.DateToString(taskBack.getCreateDate(),"yyyy-MM-dd"));
            rMap.put("state",taskBack.getProcessState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }


    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)) {
            fileId ="";
            taskback = taskBackService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            flowNumStatus = workflowService.getFlowNumStatus(keyId);
            if(taskback.getFile() != null && taskback.getFile().size()>0){
                for(FileManage f:taskback.getFile()){
                    fileId+=f.getId()+",";
                }
            }

        }

        return "read";
    }


    public String input(){
      //  Company company = usersService.getCompanyByUser();
      //  Map<String,Object> rMap = null;
        if (StringUtils.isNotEmpty(parentId)){
            taskControl = taskControlService.get(parentId);
            taskback = new TaskBack();
            taskback.setTaskControl(taskControl);
            taskback.setProcessState(FlowEnum.ProcessState.Draft);
        }
        if (StringUtils.isNotEmpty(keyId)){
            fileId ="";
            taskback = taskBackService.get(keyId);
            if(taskback.getFile() != null && taskback.getFile().size()>0){
                for(FileManage f:taskback.getFile()){
                    fileId+=f.getId()+",";
                }
            }

        } else {


        }

        return "input";
    }

    private void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            taskback = taskBackService.get(keyId);
        }else{
            taskback = new TaskBack();
            taskback.setCreater(usersService.getLoginInfo());
        }
        if(StringUtils.isNotEmpty(parentId)){
            taskControl = taskControlService.get(parentId);
            taskback.setTaskControl(taskControl);
        }
        taskback.setDegree(degree);
        taskback.setFinishTime(DataUtil.StringToDate(finishTime));
        taskback.setContent(content);
        taskback.setRemark(remark);
        List<FileManage> fileManageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds2)){
            for(String f:fileIds2.split(",")){
                fileManageList.add(fileManageService.get(f.trim()));
            }
        }
        taskback.setFile(fileManageList);
        taskback.setCompany(usersService.getLoginInfo().getCompany());
    }

    // 保存
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                taskBackService.update(taskback);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                taskBackService.save(taskback, "taskback", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }


    // 提交
    public String commit(){
        setData();
        Company company = usersService.getCompanyByUser();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);
        List<Users> usersList = null;
        if(taskControl != null){
            usersList = taskControl.getDutyMans();
            ArrayList<String> list = new ArrayList<String>();
            list.add(taskControl.getCreater().getId());
            var2.put("approvers", list);
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                taskBackService.approve(taskback, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                keyId = taskBackService.commit(taskback, "taskback", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        //先删除读者
        readersService.deleteByKeyIdBussinessKey(keyId);
        //增加归档后读者
        for(Users users:usersList){
            Readers readers = new Readers();
            readers.setUsers(users);
            readers.setBussinessKey("taskback");
            readers.setKeyId(keyId);
            readers.setType(2);
            readersService.save(readers);
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批1
    public String approve1(){
        taskback = taskBackService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

        var1.put("numStatus", 2);
        var1.put("curDutyId", curDutyId);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                taskBackService.approve(taskback, FlowEnum.ProcessState.Finished, var1, curDutyId, comment);
                if(StringUtils.equals("全部完成",taskback.getDegree())){
                    taskControl = taskback.getTaskControl();
                    taskControl.setFinish(true);
                    taskControlService.update(taskControl);
                }
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }



    /**
     * 退回
     * @return
     */
    public String reject() {
        if (StringUtils.isNotEmpty(keyId)) {
            taskback = taskBackService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("taskback");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
           // System.out.println("comment:"+comment);
             LogUtil.info("numStatus:" + numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            taskBackService.reject(taskback, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (StringUtils.isNotEmpty(keyId)) {
            taskback = taskBackService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("taskback");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:" + key);
            if(StringUtils.isEmpty(comment)){
                comment="";
            }
            taskBackService.deny(taskback, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }

    //检查新建人
    public String checkCreater(){
        Users users = usersService.getLoginInfo();
        if(users == null){
            return ajaxHtmlCallback("400", "您没有操作此文档的权限", "操作状态");
        }
        if(StringUtils.isEmpty(parentId)){
            return ajaxHtmlCallback("400", "您没有操作此文档的权限", "操作状态");
        }
        TaskControl taskControl = taskControlService.get(parentId);
        if(taskControl == null){
            return ajaxHtmlCallback("400", "您没有操作此文档的权限", "操作状态");
        }
        for(Users users1: taskControl.getDutyMans()){
            if(StringUtils.equals(users1.getId(), users.getId())){
                return ajaxHtmlCallback("200", "身份合法", "操作状态");
            }
        }
        return ajaxHtmlCallback("400", "您没有操作此文档的权限", "操作状态");
    }

    public TaskControl getTaskControl() {
        return taskControl;
    }

    public void setTaskControl(TaskControl taskControl) {
        this.taskControl = taskControl;
    }

    public TaskBack getTaskback() {
        return taskback;
    }

    public void setTaskback(TaskBack taskback) {
        this.taskback = taskback;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getFileId() {
        return fileId;
    }

    public void setFileId(String fileId) {
        this.fileId = fileId;
    }

    public String getDegree() {
        return degree;
    }

    public void setDegree(String degree) {
        this.degree = degree;
    }

    public String getFinishTime() {
        return finishTime;
    }

    public void setFinishTime(String finishTime) {
        this.finishTime = finishTime;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getFileIds2() {
        return fileIds2;
    }

    public void setFileIds2(String fileIds2) {
        this.fileIds2 = fileIds2;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }
}

